package unify.data;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.field.ForeignCollectionField;
import com.j256.ormlite.table.DatabaseTable;

@DatabaseTable(tableName = "seasons")
public class Season implements Comparable<Season> {
	@SuppressWarnings("unused")
	@DatabaseField(generatedId = true)
	private int databaseId;
	@ForeignCollectionField(eager = true, maxEagerLevel=2)
	private Collection<Episode> episodes = new ArrayList<Episode>();
	@DatabaseField
	private int number;
	@SuppressWarnings("unused")
	@DatabaseField(foreign = true, foreignAutoRefresh=true)
	private Show myShow;

	/**
	 * Ormlite no-arg constructor
	 */
	public Season() {
		super();
	}

	public Season(int number, Show myShow) {
		super();
		this.number = number;
		this.myShow = myShow;
	}

	public Episode getEpisode() {
		for(Episode episode : this.episodes) {
			return episode;
		}
		return null;
	}

	public String formatSeasonEp(int epNum) {
		String string;
		if(this.getNumber()>9) {
			string = "s" + this.getNumber();
		}
		else {
			string = "s0" + this.getNumber();
		}
		if(epNum>9) {
			string = string + "e" + epNum;
		}
		else {
			string = string + "e0" + epNum;
		}
		return string;
	}

	public List<Episode> getEpisodes() {
		List<Episode> episodeList = new ArrayList<Episode>();
		episodeList.addAll(this.episodes);
		Collections.sort(episodeList);
		return Collections.unmodifiableList(episodeList);
	}

	public Episode findEpisode(int num) {
		for(Episode episode : this.episodes) {
			if(episode.getNumber()==num) {
				return episode;
			}
		}
		return null;
	}

	public void addEpisode(int episode, String link, String linkLabel) {
		this.episodes.add(new Episode(episode, link, linkLabel, this));
	}

	public void removeEpisode(Episode episode) {
		for (Iterator<Episode> it = this.episodes.iterator(); it.hasNext();) {
			if (it.next().getNumber()==episode.getNumber()) {
				it.remove();
			}
		}
	}

	public int getNumber() {
		return number;
	}

	@Override
	public int compareTo(Season season) {
		return this.number - season.getNumber();
	}

}
